#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
###----------1、文件说明----------### 
''' 
* 说明：基础使用的软件安装
* 时间：2025-04-23
* 文件：
* 作者：Smile
* 版本：0.1
* 库版本: 
 - conan: 2.14.0
* 备注： 
'''
import os,sys
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.system import package_manager
from pprint import pprint
import platform
import importlib

def getClassValue(sclass):
    '''
    获取类的子属性
    版本: 0.1
    :param sclass:
    :return:
    '''
    from types import FunctionType, BuiltinFunctionType, MethodType

    print("Get Class ", type(sclass))
    for i in dir(sclass):
        tmp = getattr(sclass, i)
        if isinstance(tmp, FunctionType) or isinstance(tmp, BuiltinFunctionType):
            print(i, "\t", type(tmp), "Function")
        else:
            print(i, "\t", type(tmp), tmp)

manager_mapping = {"Apt": ["Linux", "ubuntu", "kylin", "debian", "raspbian", "linuxmint", 'astra', 'elbrus', 'altlinux', 'pop'],
                    "Apk": ["alpine"],
                    "Yum": ["pidora", "scientific", "xenserver", "amazon", "oracle", "amzn",
                            "almalinux", "rocky"],
                    "Dnf": ["fedora", "rhel", "centos", "mageia", "nobara"],
                    "Brew": ["Darwin"],
                    "PacMan": ["arch", "manjaro", "msys2", "endeavouros"],
                    "Chocolatey": ["Windows"],
                    "Zypper": ["opensuse", "sles"],
                    "Pkg": ["freebsd"],
                    "Pkgutil": ["Solaris"]}

class SoftConfigRecipe(ConanFile):
    name = "softconfig"
    version = "0.1"
    package_type = "library"

    # 个人信息
    license = "MIT"
    author = "<OSmile> <whghcyx@outlook.com>"
    url = "https://whg555.github.io"
    description = "readme description"
    topics = ("<Put some tag here>", "<here>", "<and here>")

    # 安装包
    packages = {
        "ubuntu" :  {
            "default" : ["gcc","g++","make","aptitude","openssh-server","net-tools", "vim-gtk", "ctags","p7zip-full",
                        "terminator","unzip","tree","git","iotop","htop","speedometer","nethogs","python3-pip", "python-pip"], # 当前系统通用的包
            "20" : ["gcc","g++","make","aptitude","openssh-server","net-tools", "vim-gtk", "ctags", "p7zip-full",
                "terminator","unzip","tree","git","iotop","htop","speedometer","nethogs","python3-pip"], # 特定版本号的包
            "22": ["gcc", "g++", "make", "aptitude", "openssh-server", "net-tools", "vim-gtk", "universal-ctags", "p7zip-full",
                   "terminator", "unzip", "tree", "git", "iotop", "htop", "speedometer", "nethogs", "python3-pip"], # 特定版本号的包
        },
        "kylin" : {
            "default" : ["gcc","g++","make","aptitude","openssh-server","net-tools", "vim-gtk", "ctags","p7zip-full",
                        "terminator","unzip","tree","git","iotop","htop","speedometer","nethogs","python3-pip", "python-pip"], # 当前系统通用的包
            "v10" :  ["gcc","g++","make","aptitude","openssh-server","net-tools", "vim-gtk", "ctags","p7zip-full",
                        "terminator","unzip","tree","git","iotop","htop","speedometer","nethogs","python3-pip"], # 当前系统通用的包
        },
        "default" : {
            "default" : ["gcc","g++","make","aptitude","openssh-server","net-tools", "vim-gtk", "ctags", "p7zip-full",
                "terminator","unzip","tree","git","iotop","htop","speedometer","nethogs","python3-pip", "python-pip"]
        }
    }

    # 二进制配置
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}

    # Sources are located in the same place as this recipe, copy them to the recipe
    # exports_sources = "CMakeLists.txt", "src/*", "include/*"

    def config_options(self):
        '''
        针对系统，对配置命令做一些修改
        <1>conan install .
        <1>conan create .
        <test><1>conan create .
        '''
        print("\033[43;34mOSmile-->", "config_options", "\033[0m")
        print(">OS System Info")
        pprint(self.settings.values_list)
        pprint(self.serialize())
        print("self.conf", self.conf)

        # 获取系统版本信息
        os_name = platform.system()
        self.os_name = self.os_version = self.os_base =  ""
        self.os_base = os_name
        if os_name in ["Linux", "FreeBSD"]:
            import distro
            self.os_name = distro.id() or os_name
            self.os_version = distro.version(best=True).split(".")[0]
        elif os_name == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            self.os_name = "msys2"
            self.os_version = ""
        print("System   -->", self.os_base)
        print("OSSystem -->", self.os_name)
        print("Version  -->", self.os_version)

    def configure(self):
        '''
        <2>conan install .
        <2>conan create .
        <test><2>conan create .
        '''
        print("\033[43;34mOSmile-->", "configure", "\033[0m")
        if self.os_name == "kylin":
            self.conf.define("tools.system.package_manager:tool", "apt-get")
        self.conf.define("tools.system.package_manager:mode", "install")
        self.conf.define("tools.system.package_manager:sudo", True)

    def system_requirements(self):
        '''
        安装需要的软件
        <4>conan install .
        <4>conan create .
        <test><4>conan create .
        '''
        print("\033[43;34mOSmile-->", "system_requirements", "\033[0m")
        if platform.system() in ["Linux", "FreeBSD"]:
            # 获取编译工具
            for tool, distros in manager_mapping.items():
                if self.os_name in distros:
                    break
            # 查找需要安装的包
            os_name_key = self.os_name if (self.os_name in self.packages.keys()) else "default"
            os_version_key = self.os_version if (self.os_version in self.packages[os_name_key].keys()) else "default"
            softs = self.packages.get(os_name_key).get(os_version_key)
            print("安装软件包-->", softs)
            softtool = getattr(package_manager, tool)(self)
            softtool.install(softs, update=False, check=True)
        elif platform.system() == "Windows" and self._conanfile.settings.get_safe("os.subsystem") == "msys2":
            os_name = "msys2"

    def generate(self):
        '''
        配置已经安装的软件
        <5>conan install .
        <5>conan create .
        '''
        print("\033[43;34mOSmile-->", "generate", "\033[0m")
        print(os.environ["HOME"])
        self.run("pwd")

        self.run(f"sudo chown {os.getlogin()}:{os.getlogin()} /opt", cwd=os.environ["HOME"])
        self.run("sudo mkdir /data", cwd=os.environ["HOME"])
        self.run(f"sudo chown {os.getlogin()}:{os.getlogin()} /data", cwd=os.environ["HOME"])

        # pip配置
        try:
            self.run("pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple")
            self.run("sudo pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple")
        except:
            pass

        # vim配置
        self.run("wget https://gitee.com/whghcyx/file-sharing/releases/download/newsoft/vim.tar.gz", cwd=os.environ["HOME"])
        self.run("tar -xzvf vim.tar.gz", cwd=os.environ["HOME"])

        # root用户配置
        self.run('sudo cp vim.tar.gz /root', cwd=os.environ["HOME"])
        self.run("sudo tar -xzvf /root/vim.tar.gz -C /root", cwd=os.environ["HOME"])
        self.run("rm vim.tar.gz", cwd=os.environ["HOME"])

        # termintor配置
        self.run("mkdir -p .config/terminator", cwd=os.environ["HOME"])
        sconfig = '''
[global_config]
  handle_size = 20
  scroll_tabbar = True
  title_hide_sizetext = True
  title_transmit_fg_color = "#f3f3f3"
  title_transmit_bg_color = "#4e9a06"
  title_inactive_fg_color = "#babdb6"
  title_inactive_bg_color = "#4b4b4b"
  inactive_color_offset = 1.0
  enabled_plugins = ActivityWatch,
  suppress_multiple_term_dialog = True
[keybindings]
  switch_to_tab_1 = <Alt>1
  switch_to_tab_2 = <Alt>2
  switch_to_tab_3 = <Alt>3
  switch_to_tab_4 = <Alt>4
  switch_to_tab_5 = <Alt>5
  switch_to_tab_6 = <Alt>6
  switch_to_tab_7 = <Alt>7
  switch_to_tab_8 = <Alt>8
  switch_to_tab_9 = <Alt>9
  switch_to_tab_10 = None
  edit_window_title = <Primary><Alt>w
  edit_tab_title = <Primary><Alt>s
  edit_terminal_title = <Primary><Alt>x
[profiles]
  [[default]]
    icon_bell = False
    background_color = "#282828"
    background_darkness = 1.0
    background_type = transparent
    cursor_shape = ibeam
    cursor_color = "#e8e8e8"
    font = Ubuntu Mono 14
    foreground_color = "#e8e8e8"
    scroll_background = False
    scrollback_lines = 3000
    palette = "#292424:#ef2929:#8ae234:#cdcd00:#1e90ff:#cd00cd:#00cdcd:#d6d9d4:#4c4c4c:#868e09:#00ff00:#ffff00:#4682b4:#ff00ff:#00ffff:#ffffff"
    use_system_font = False
[layouts]
  [[default]]
    [[[window0]]]
      type = Window
      parent = ""
    [[[child1]]]
      type = Terminal
      parent = window0
      profile = default
[plugins]
        '''
        self.run("rm .config/terminator/config", cwd=os.environ["HOME"], ignore_errors=True)
        for cfg in sconfig.split("\n"):
            self.run("echo '" + cfg + "' >> .config/terminator/config", cwd=os.environ["HOME"])

        if self.os_name == "ubuntu":
            # 关闭更新
            print(">>>关闭系统更新<<<")
            if os.path.exists("/etc/apt/apt.conf.d/20auto-upgrades"):
                self.run("sudo sed -i 's/1/0/g' /etc/apt/apt.conf.d/20auto-upgrades", cwd=os.environ["HOME"])
            if os.path.exists("/etc/apt/apt.conf.d/10periodic"):
                self.run("sudo sed -i 's/1/0/g' /etc/apt/apt.conf.d/10periodic", cwd=os.environ["HOME"])
            self.run("sudo apt-get remove update-notifier", cwd=os.environ["HOME"])
            self.run("sudo systemctl stop unattended-upgrades", cwd=os.environ["HOME"])
            self.run("sudo systemctl disable unattended-upgrades", cwd=os.environ["HOME"])
            self.run("sudo systemctl status unattended-upgrades", cwd=os.environ["HOME"], ignore_errors=True)
            self.run("sudo dpkg-reconfigure -plow unattended-upgrades", cwd=os.environ["HOME"])
